<!--
 * @FilePath: EditModule.vue
 * @Author: jack
 * @Date: 2024-05-14 11:55:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-08 19:01:12
 * Copyright: 2024 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 
-->
<template>
    <Model :title="editId ? '编辑数据' : '添加数据'" :modelShow="props.modelShow" width="700px" @cancel="Cancel(ruleFormRef)"
        @confirm="Confirm(ruleFormRef)">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="82px" status-icon>
            <el-row :gutter="10">
                <el-col :span="24">
                    <el-form-item label="名称" prop="name">
                        <el-input clearable placeholder="请输入名称" v-model="ruleForm.name">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="ruleForm.type" @change="seletChange"
                            :disabled="loading == true || loading2 == true" style="width:100%;" clearable
                            placeholder="请选择类型">
                            <el-option label="图片" value="1"></el-option>
                            <el-option label="视频" value="2"></el-option>
                            <el-option label="网址链接" value="3"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="Number(ruleForm.type) == 3">
                    <el-form-item label="网址链接" prop="link">
                        <el-input v-model="ruleForm.link" placeholder="请输入网址链接地址"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="Number(ruleForm.type) == 1">
                    <el-form-item label="上传图片" prop="pic" :style="ruleForm.pic.length > 0 ? 'margin-bottom: 0px;' : ''">
                        <div class="uploadList">
                            <div style="display: inline-block;height: 72px;margin-right: 20px;">
                                <el-upload class=" avatar-uploader" :show-file-list="false"
                                    :on-success="handleAvatarSuccess" :http-request="uploadAvatorAdd2"
                                    :before-upload="beforeAvatarUpload">
                                    <el-icon class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                    <div>点击上传图片</div>
                                </el-upload>
                            </div>
                            <div class="items" style="margin-bottom: 20px" v-for="(item, index) in ruleForm.pic"
                                :key="index" @mouseenter="mouserIndex2 = index" @mouseleave="mouserIndex2 = -1">
                                <el-image :src="item" fit="cover" style="width: 100%;height: 100%;"></el-image>
                                <transition name="fade" mode="out-in">
                                    <div class="model-img-box" v-if="mouserIndex2 == index">
                                        <div class="mine-flex-box">
                                            <el-icon @click="showImage2(item)">
                                                <View />
                                            </el-icon>
                                            <span></span>
                                            <el-icon @click="handleRemove2(index)">
                                                <Delete />
                                            </el-icon>
                                        </div>
                                    </div>
                                </transition>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="Number(ruleForm.type) == 2">
                    <el-form-item label="上传方式" required>
                        <el-radio-group v-model="ruleForm.uploadType">
                            <el-radio-button label="1">视频链接地址</el-radio-button>
                            <el-radio-button label="2">本地上传视频</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="视频链接" prop="video" v-if="Number(ruleForm.uploadType) == 1">
                        <el-input @change="videoLinkChange" v-model="ruleForm.video" placeholder="请输入视频链接地址"></el-input>
                    </el-form-item>
                    <el-form-item label="上传视频" prop="video" v-if="Number(ruleForm.uploadType) == 2">
                        <el-input v-model="ruleForm.video" disabled tyle="max-width: 600px" placeholder="请上传视频"
                            class="input-with-select">
                            <template #prepend>
                                <el-upload :show-file-list="false" :on-success="handleAvatarSuccess"
                                    :http-request="uploadAvatorAdd2" :before-upload="beforeAvatarUpload2">
                                    <el-button type="primary" style="padding: 0 15px;" :link="true">
                                        点击上传
                                    </el-button>
                                </el-upload>
                            </template>
                            <template #append>
                                <div class="align-items" v-if="!loading" @click="toCopy">
                                    <el-icon>
                                        <DocumentCopy />
                                    </el-icon>
                                    <span style="margin-left: 5px;">复制地址</span>
                                </div>
                                <el-button v-else type="primary" class="align-items" :loading="loading">已上传{{
        percentageNum }}%</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="ruleForm.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </Model>
    <!-- 查看图片 -->
    <el-image-viewer v-if="showViewer" @close="closeViewer" :url-list="srcList"></el-image-viewer>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadInstance } from 'element-plus'
import { UploadProps, UploadRequestOptions } from 'element-plus'
import * as imageConversion from 'image-conversion'; // 图片压缩
import upload from '../../../util/OSSUpload'
import $util from '../../../util/util'
import { getMaterList, materialSetting } from '../../Api/index'
interface PropsType {
    // 是否显示弹窗
    modelShow?: boolean
    dataList?: any
    typeId?: any
    editIndex?: number
}
const props = withDefaults(defineProps<PropsType>(), {
    modelShow: false,
    dataList: [],
    typeId: '',
    editIndex: -1
})
const emit = defineEmits<EmitType>()
interface EmitType {
    (e: 'CancelModule'): void
    (e: 'getList'): void
    (e: 'changeData', item: any): void
}
watch(
    () => [props.editIndex, props.modelShow],
    (newValue, oldValue) => {
        if (props.modelShow) {
            if (props.editIndex !== -1) {
                // 编辑
                ruleForm.value = JSON.parse(JSON.stringify(props.dataList[props.editIndex]))
            } else {
                ruleForm.value.id = $util.generateUniqueId(props.dataList)
            }
        }
    },
    { deep: true }
)
const ruleForm = ref<any>({
    id: '',
    name: '',
    type: '',
    pic: [],
    local_pic: [],
    uploadType: '1',
    video: '',
    local_video: '',
    link: '',
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入大屏名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
    pic: [{ required: true, message: '请上传图片', trigger: 'blur' }],
    video: [{ required: true, message: '请上传视频', trigger: 'blur' }],
})
const editId = ref<string>('')
// 查看图片
const mouserIndex = ref(-1)
const mouserIndex2 = ref(-1)
const srcList = ref<any>([])
const showViewer = ref(false)// 显示查看器
const percentageNum = ref<number>(0) // 视频上传进度
const loading = ref<boolean>(false)
const loading2 = ref<boolean>(false)
const showImage2 = (item: any) => {
    srcList.value = []
    srcList.value.push(item)
    showViewer.value = true
}
const handleRemove2 = (index: number) => {
    ruleForm.value.local_pic = []
    ruleForm.value.pic.splice(index, 1)
}
const closeViewer = () => {
    showViewer.value = false
}
const seletChange = (val: any) => {
    if (Number(val) === 1) {
        // 如果是选择的图片
        ruleForm.value.video = ''
        ruleForm.value.local_video = []
    } else {
        ruleForm.value.pic = []
        ruleForm.value.local_pic = []
    }
}
// 复制链接地址
const toCopy = () => {
    const url = ruleForm.value.video
    var domUrl = document.createElement('input')
    domUrl.value = url
    domUrl.id = 'creatDom'
    document.body.appendChild(domUrl)
    domUrl.select() // 选择对象
    document.execCommand('Copy') // 执行浏览器复制命令
    ElMessage.success('已复制成功，可粘贴！')
}
// 上传图片前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
    const typeList = ['image/jpeg', 'image/png']
    const isTypeValid = typeList.includes(rawFile.type)
    // const isLt2M = rawFile.size / 1024 / 1024 < 2
    if (!isTypeValid) {
        ElMessage.error('请上传正确的图片!')
        return false
    }
    // if (!isLt2M) {
    //     Message.error('上传图片大小不能超过2M!')
    //     return false
    // }
    const params: any = { size: 200, type: 'image/jpeg' }
    return new Promise(async (resolve, reject) => {
        if (rawFile.size / 1024 > 300) { // 大于 300 kb 就压缩
            let file: any = await pngToWhiteBg(rawFile)
            const fileOfBlob = new File([file], `${new Date().getTime()}.png`, { type: file.type })
            imageConversion.compressAccurately(fileOfBlob, 250).then(res => {
                console.log(res)
                resolve(res)
            })
        } else if (isTypeValid) {
            // 无需压缩直接返回原文件
            resolve(rawFile)
        } else {
            reject()
        }
    })
}
// 上传视频前验证
const beforeAvatarUpload2: UploadProps['beforeUpload'] = rawFile => {
    if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(rawFile.type) == -1) {
        ElMessage.error('上传视频只能是 mp4、ogg、flv、avi、wmv、rmvb 格式!')
        return false;
    }
    return true
}
const pngToWhiteBg = async (file: any) => {
    let read = new FileReader();
    read.readAsDataURL(file); // 文件转base64
    return new Promise((resolve, reject) => {
        read.onload = (e: any) => {
            let img: any = new Image();
            img.src = e.target.result;
            img.onload = async () => {
                // 生成canvas
                let canvas = document.createElement("canvas");
                let context: any = canvas.getContext("2d");
                // 绘制图片到canvas上
                canvas.width = img.width;
                canvas.height = img.height;

                // 在canvas绘制前填充白色背景
                context.fillStyle = "#fff";
                context.fillRect(0, 0, canvas.width, canvas.height);
                context.drawImage(img, 0, 0);
                let base64 = canvas.toDataURL(file["type"], 1);
                let newFile = dataUrlToFile(base64);
                resolve(newFile);
            }
        }
    })
}
const dataUrlToFile = async (dataurl: any) => {
    let arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
}
const videoLinkChange = () => {
    ruleForm.value.local_video = ''
}
// 上传图片或者视频
const uploadAvatorAdd2 = async (options: UploadRequestOptions) => {
    if (Number(ruleForm.value.type) === 1) {
        loading2.value = true
    } else {
        loading.value = true
    }
    upload(options.file, Number(ruleForm.value.type) === 1 ? 'pic' : 'video', (res: any) => {
        if (Number(ruleForm.value.type) === 1) {
            // 上传图片
            ruleForm.value.local_pic = []
            ruleForm.value.pic.push(res.inch)
            mouserIndex2.value = -1
            loading2.value = false
        } else {
            // 上传视频
            ruleForm.value.local_video = ''
            loading.value = false
            ruleForm.value.video = res.inch
        }
    },
        (error: any) => {
            loading2.value = false
            loading.value = false
            console.log(error)
        },
        (percent: any) => {
            if (Number(ruleForm.value.type) === 2) {
                percentageNum.value = percent.percent
            }
        }
    )
}
// 上传视频
const Cancel = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    reset()
    emit('CancelModule')
}
const reset = () => {
    ruleForm.value = {
        id: '',
        name: '',
        type: '',
        pic: [],
        local_pic: [],
        uploadType: '1',
        video: '',
        local_video: '',
        link: '',
    }
}
// 点击确定编辑或者新增
const Confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid: any) => {
        if (valid) {
            let arr: any = []
            if (props.editIndex !== -1) {
                // 如果是编辑
                arr = props.dataList
                arr[props.editIndex] = ruleForm.value
            } else {
                // 如果是添加
                arr = props.dataList
                arr.unshift(ruleForm.value)
            }
            const res: any = await materialSetting({ type_id: props.typeId, content: arr })
            if (res.code !== 1) return ElMessage.error(res.message)
            emit('getList')
            ElMessage.success(res.message)
            reset()
            emit('CancelModule')
        } else {
            console.log('error submit!')
        }
    })
}
onMounted(() => {
})
</script>
<style lang="scss" scoped>
.uploadList {
    display: flex;
    flex-flow: wrap;
    width: 100%;

    .items {
        width: 120px;
        height: 72px;
        background: #EEEEEE;
        display: inline-block;
        margin: 0 20px 0 0;
        border-radius: 4px;
        border: 1px dashed #DCDCDC;
        position: relative;
        padding: 6px;
        box-sizing: border-box;

        .el-image {
            border-radius: 4px;
            background: #ffffff
        }

        .model-img-box {
            background: rgba(0, 0, 0, 0.5);
            width: 100%;
            height: 72px;
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            border-radius: 4px;
            z-index: 9;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;

            i {
                color: #fff;
                font-size: 16px;
            }

            .mine-flex-box {
                display: flex;
                width: 65%;
                justify-content: space-between;
                align-items: center;

                .el-icon {
                    transition: all 1s;
                    font-weight: bold;
                }

                span {   width: 1px;
                    margin: 0 7px;
                    height: 12px;
                    background: rgba(255, 255, 255, 0.9);
                    display: inline-block;
                }

                .el-icon:first-of-type:hover {
                    transform: scale(1.2);
                }

                .el-icon:last-of-type:hover {
                    transform: scale(1.2);
                }

                :deep(.avatar-uploader) {
                    width: 16px;
                    height: 16px;
                    margin: 0px;


                }

                :deep(.avatar-uploader .el-upload) {
                    width: 16px;
                    height: 16px;
                    border: none;
                    background-color: transparent;
                }
            }

            .zoom-big-box {
                display: flex;
                align-items: center;
                transition: all 1s;
            }
        }
    }

    .uploadBtn {
        text-align: center;
        display: flex;
        align-items: center;
        flex-flow: column;
    }
}

:deep(.avatar-uploader .el-upload) {
    width: 120px;
    height: 72px;
    background: #EEEEEE;
    border-radius: 4px;
    border: 1px dashed #DCDCDC;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.4);
    box-sizing: border-box;
}

:deep(.el-icon.avatar-uploader-icon) {
    color: #000000;
    margin-bottom: 3px;
    font-size: 14px;
    font-weight: 600;
}

:deep(.avatar-uploader) {
    margin: 0px;
    width: 120px;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: #ffffff;
    box-shadow: 0 0 0 0.0625rem var(--el-input-border-color, var(--el-border-color)) inset;
}

:deep(.el-progress-circle) {
    width:20px!important;
    height:20px!important;
}
:deep(.el-progress__text){
    display:none;
}
</style>
